package com.compass.doctor.ui.mine

import android.content.Context
import android.content.Intent
import android.os.Build.VERSION_CODES.P
import android.os.Bundle
import android.text.TextUtils
import androidx.activity.viewModels
import com.compass.doctor.R
import com.compass.doctor.base.BaseVBActivity
import com.compass.doctor.databinding.ActivityEditUserDataBinding
import com.compass.doctor.ui.home.viewmodel.MedicalCareViewModel
import com.compass.doctor.ui.mine.viewmodel.MineViewModel
import com.compass.doctor.utils.SelectPicturesUtil
import com.compass.framework.constant.KEY_DOCTOR_AUTHSTATE
import com.compass.framework.constant.KEY_DOCTOR_AUTH_REASON
import com.compass.framework.constant.REFRESH_USER
import com.compass.framework.dialog.ChooseSexDialog
import com.compass.framework.dialog.CommonMessageDialog
import com.compass.framework.ext.dp2px
import com.compass.framework.ext.gone
import com.compass.framework.ext.onClick
import com.compass.framework.ext.visible
import com.compass.framework.glide.setUrlRound
import com.compass.framework.manager.UserInfoManager
import com.compass.framework.toast.TipsToast
import com.compass.framework.utils.LiveDataBus
import com.compass.framework.utils.getStringFromResource
import com.hjq.permissions.OnPermissionCallback
import com.hjq.permissions.Permission
import com.hjq.permissions.XXPermissions
import com.luck.picture.lib.entity.LocalMedia
import com.luck.picture.lib.interfaces.OnResultCallbackListener
import java.io.File


/**
 * Description： 编辑资料界面
 * Date:2024/7/12 21:09
 */
class EditUserDataActivity : BaseVBActivity<ActivityEditUserDataBinding>() {


    companion object {
        fun start(context: Context,auditStatus:Int?,reason:String?) {
            val intent = Intent(context, EditUserDataActivity::class.java)
            intent.putExtra(KEY_DOCTOR_AUTHSTATE,auditStatus)
            intent.putExtra(KEY_DOCTOR_AUTH_REASON,reason)
            context.startActivity(intent)
        }
    }

    private val medicalCareViewModel: MedicalCareViewModel by viewModels()
    private val mineViewModel: MineViewModel by viewModels()

    private var doctorId: String? = null //医生id
    private var doctorName: String? = null //姓名
    private var doctorSex: String? = null //性别
    private var idCardPositive: String? = null //份证照片(正面)
    private var idCardReverse: String? = null //身份证照片(反面)
    private var licensedPositive: String? = null //医生执业证(正面)
    private var licensedReverse: String? = null //医师执业证(反面)
    private var idNumber: String? = null //身份证号
    private var licenseNumber: String? = null //医师资格证号
    private var mPicType: Int = 1//图片类型

    override fun initView(savedInstanceState: Bundle?) {

    }


    override fun initData() {
        doctorId = UserInfoManager.getUserInfo()?.id
        //只有在审核拒绝的状态需要查询信息
        val authState =  intent.getIntExtra(KEY_DOCTOR_AUTHSTATE,-1)
        val reason = intent.getStringExtra(KEY_DOCTOR_AUTH_REASON)
        // 0待审核    1审核中    2已通过  -1已拒绝
        if(!doctorId.isNullOrEmpty() && authState== -1){
            mineViewModel.getDoctorAuthInfo()
            if(!reason.isNullOrEmpty()){
                //被拒绝
                mBinding.auditReason.text = reason
                mBinding.llAuditInfo.visible()
            }else{
                mBinding.llAuditInfo.gone()
            }
        }
        mineViewModel.updateExamineLiveData.observe(this) {
            it?.let {
                LiveDataBus.get().with(REFRESH_USER).postValue(REFRESH_USER)
                showToast("上传成功，请耐心等待审核")
                finish()
            }
            dismissLoading()

        }

        medicalCareViewModel.updateLiveData.observe(this) {
            dismissLoading()
            when (mPicType) {
                1 -> {
                    idCardPositive = it
                }

                2 -> {
                    idCardReverse = it
                }

                3 -> {
                    licensedPositive = it
                }

                4 -> {
                    licensedReverse = it
                }
            }
        }

        mineViewModel.userExamineLiveData.observe(this){
            if (it!=null){
                mBinding.apply {
                    doctorName = it.doctorName
                    doctorSex = it.doctorSex.toString()
                    idCardPositive = it.idCardPositive
                    idCardReverse = it.idCardReverse
                    licensedPositive = it.licensedPositive
                    licensedReverse = it.licensedReverse

                    etName.setText(it.doctorName)
                    if(it.doctorSex!=0){
                        tvSex.text = it.getSexString()
                    }else{
                        tvSex.text = "请选择"
                    }
                    cardFront.setUrlRound(it.idCardPositive, dp2px(5f))
                    cardBack.setUrlRound(it.idCardReverse, dp2px(5f))
                    licensedFront.setUrlRound(it.licensedPositive, dp2px(5f))
                    licensedBack.setUrlRound(it.licensedReverse, dp2px(5f))

                }
            }
        }

        if(!reason.isNullOrEmpty()){
            mBinding.auditReason.apply {
                ellipsize = TextUtils.TruncateAt.MARQUEE
                setSingleLine(true)
                requestFocus()
                marqueeRepeatLimit = -1
            }
        }

    }


    override fun intListener() {
        mBinding.clSex.onClick {
            showSelectSexDialog()

        }
        mBinding.cardFront.onClick {
            //上传身份证正面
            isGranted(1)
        }
        mBinding.cardBack.onClick {
            //反面
            isGranted(2)
        }
        mBinding.licensedFront.onClick {
            isGranted(3)
        }

        mBinding.licensedBack.onClick {
            isGranted(4)
        }
        mBinding.tvConfirm.onClick {

            doctorName = mBinding.etName.text.toString().trim()
            if (doctorName.isNullOrEmpty()) {
                showToast("请输入您的姓名")
                return@onClick
            }
            if (doctorSex.isNullOrEmpty()) {
                showToast("请选择性别")
                return@onClick
            }
            if (idCardPositive.isNullOrEmpty()) {
                showToast("请上传您的身份证正面照片")
                return@onClick
            }
            if (idCardReverse.isNullOrEmpty()) {
                showToast("请上传您的身份证反面照片")
                return@onClick
            }
            if (licensedPositive.isNullOrEmpty()) {
                showToast("请上传你的医师执业证照片")
                return@onClick
            }
            if (licensedReverse.isNullOrEmpty()) {
                showToast("请上传你的医师执业证注册页")
                return@onClick
            }


            showLoading()
            mineViewModel.updateExamineInfo(
                doctorId,
                doctorName,
                doctorSex,
                idCardPositive,
                idCardReverse,
                licensedPositive,
                licensedReverse
            )
        }


    }

    /**
     * 判断是否有权限
     * @param picType 照片类型
     */
    private fun isGranted(picType: Int) {
        mPicType = picType
        //判断是否有权限
        if (XXPermissions.isGranted(
                this,
                Permission.READ_EXTERNAL_STORAGE,
                Permission.WRITE_EXTERNAL_STORAGE,
                Permission.CAMERA
            )
        ) {
            showChoosePhotoDialog(picType)
        } else {
            CommonMessageDialog.Builder(this)
                .setTitle(getStringFromResource(R.string.permission_explain))
                .setMessage(getStringFromResource(R.string.image_permission_logs))
                .setConfirm(getStringFromResource(com.compass.framework.R.string.default_confirm))
                .setCancel(getString(com.compass.framework.R.string.default_cancel))
                .setonCancelListener {
                    it?.dismiss()
                }
                .setonConfirmListener {
                    showChoosePhotoDialog(picType)
                    it?.dismiss()
                }.create().show()
        }
    }

    /**
     * 选择图片弹框
     */
    private fun showChoosePhotoDialog(picType: Int) {

        XXPermissions.with(this)
            //小米应用市场不允许提前获取相册拍照权限，这里先获取存储权限，进入到相册选择页面点击拍照按钮时在获取拍照权限
            .permission(Permission.READ_EXTERNAL_STORAGE)
            .permission(Permission.WRITE_EXTERNAL_STORAGE)
            .permission(Permission.CAMERA)
            .unchecked()
            .request(object : OnPermissionCallback {
                override fun onGranted(permissions: MutableList<String>, allGranted: Boolean) {
                    if (!allGranted) {
                        TipsToast.showTips(R.string.default_agree_permission)
                        return
                    }

                    SelectPicturesUtil.selectPicturesCrop(
                        this@EditUserDataActivity,
                        callbackListener = object : OnResultCallbackListener<LocalMedia> {
                            override fun onResult(result: ArrayList<LocalMedia?>) {
                                val avatarPath = result[0]?.availablePath
                                when (picType) {
                                    1 -> {
                                        mBinding.cardFront.setUrlRound(avatarPath, dp2px(5f))
                                    }

                                    2 -> {
                                        mBinding.cardBack.setUrlRound(avatarPath, dp2px(5f))
                                    }

                                    3 -> {
                                        mBinding.licensedFront.setUrlRound(avatarPath, dp2px(5f))
                                    }

                                    4 -> {
                                        mBinding.licensedBack.setUrlRound(avatarPath, dp2px(5f))
                                    }
                                }
                                showLoading()
                                medicalCareViewModel.upload(File(avatarPath))
                            }

                            override fun onCancel() {

                            }
                        })

                }

                override fun onDenied(permissions: MutableList<String>, doNotAskAgain: Boolean) {
                    TipsToast.showTips(R.string.default_agree_permission)
                }
            })
    }


    /**
     * 性别选择弹框
     */
    private fun showSelectSexDialog() {

        ChooseSexDialog.Builder(this).setOnSexChooseCall { s, i ->
            mBinding.tvSex.text = s
            doctorSex = i.toString()
        }.show()


    }


}